Main
2022-09-18

Shorter Hacks 16: IPython Autoreload

When developing some python code and testing it in IPython, I love the autoreload feature of IPython. When enabled it will reload imported modules automatically. So you will always use the newest version of your code. It even patches modifications on class methods into existing class instances. To enable it first load it with %load_ext autoreload, then enable it with %autoreload 2 – See the documentation for explanations of the options and how to autoreload only selected imports. Here is a code sniped to demonstrate its power:

In [1]: %load_ext autoreload

In [2]: %autoreload 2

In [3]: from test import Foo

In [4]: foo = Foo()

In [5]: foo.bar()
1

# Edit the code
In [6]: foo.bar()
2

You can put the following into your ipython_config¹ to load and enable the autoreload extension automatically on startup (I only use the first line):

c.InteractiveShellApp.extensions.append("autoreload")
c.InteractiveShellApp.exec_lines = ["%autoreload 2"]



1: Ether

en shorterhacks python ipython

The series Shorter Hacks consists of tips and tricks for Linux nerds. Flags, hacks, and features of everyday tools that you might not know already, but that will enrich your life. I currently have a list of around 40 hacks I collected and plan to publish them roughly weekly. In order for this series to continue, please send me your best trick(s). The focus is not on fancy new tools or extensive rc-file content, but little known features in software most people already use. Send them to michael bei schoenitzer punkt de.
This blog has an Atom-Feed and I plan to also post the Shorter Hacks articles on Mastodon and Twitter.

Creative Commons License "Shorter Hacks 16 IPython Autoreload" by Michael F. Schönitzer is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.